#/usr/bin/python
# coding: utf8

import time
from  PAM30 import PAM30
#import PAM30
import sys
import win32api
import win32con
import ConfigParser

reload(sys)
sys.setdefaultencoding("utf-8")


def ordd(str):
    '''
    解决键盘码不对应问题,不知道别的电脑有没有这个问题
    '''
    t = ord(str)
    #65到90是A到Z
    if(t>90):
        return t-32
    else:
        return t


def typeme(passw):
    '''
    模拟人工输入,自动输入参数字符串到焦点窗口
    '''
    psht = len(passw)
    for j in range(psht):
        win32api.keybd_event(ordd(passw[j]), 0, 0, 0)
        time.sleep(0.5)
        win32api.keybd_event(ordd(passw[j]), 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(0.5)


def lgTaobao(username, userpass):
    '''
    使用指定用户名密码（在IE）登录淘宝
    '''
    lgurl = 'http://login.taobao.com/member/login.jhtml?spm=a1z01.1000834.0.66&redirect_url=http%3A%2F%2Ftaojinbi.taobao.com%2Fhome%2Faward_exchange_home.htm'
    ie.navigate(lgurl)
    ie.setTextBox('TPL_username', username.decode('utf-8'))
    time.sleep(1)
    ie.setCheckBox('J_SafeLoginCheck', 0)
    time.sleep(1)
    bt = ie.findElement('button', 'id', 'J_SubmitStatic')
    ie.clickElement(bt)
    #ie.setTextBox('TPL_password', userpass)
    typeme(userpass)
    time.sleep(0.5)
    bt = ie.findElement('button', 'id', 'J_SubmitStatic')
    ie.clickElement(bt)
    if(ie.findText(username)):
        return True
    else:
        return False


def getJinbi():
    '''
    默认登陆状态，然后自动到taojinbi.taobao.com
    点击领取金币
    '''
    print 'ling jin bi'
    time.sleep(3)
    ie.stop()
    #jbi = ie.findElement('a', 'id', 'J_CoinGrantBtn')
    #isC = ie.clickElement(jbi)
    isC = ie.clickLink('J_CoinGrantBtn')
    if(isC):
        win32api.Beep(3000, 2000)
        return True
    else:
        win32api.Beep(300, 200)
        return False

config = ConfigParser.ConfigParser()
config.read('sys.ini')
taobaoid = config.get("global", "taobaoid")
loginpass = config.get("global", "loginpass")
paypass = config.get("global", "paypass")
ie = PAM30.PAMIE()
time.sleep(2)
lgTaobao(taobaoid, loginpass)
time.sleep(2)
if(getJinbi()):
    print 'OK'
else:
    print 'bu ok'
